package com.bsoft.apiservice.service;


import com.bsoft.apiservice.dto.*;
import com.fasterxml.jackson.core.JsonProcessingException;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class SpecimenTransportService {


    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    private static final String CREATE_ORDER_URL = "http://172.16.40.228:8671/cds/sl/openapi/cds/v1/lis/specimen/createOrder";

    private static final String CANCEL_ORDER_URL = "http://172.16.40.228:8671/cds/sl/openapi/cds/v1/lis/specimen/cancelOrder";

    public ApiResponse createSpecimenOrder(PackageReq  request) throws JsonProcessingException {
        List<SpecimenOrderRequest> specimenOrderRequestList = new ArrayList<>();
        SpecimenOrderRequest specimenOrderRequest = new SpecimenOrderRequest();

        String parcelCode = request.getParcelCode();
        log.info("parcelCode:"+parcelCode);

        SpecimenOrderRequest.BarCodeInfo barCodeList = new SpecimenOrderRequest.BarCodeInfo();
        List<SpecimenOrderRequest.BarCodeInfo> barCodeInfo = new ArrayList<>();
        String sjqid="";
        String DOCTADVISENO="";
        String EXECUTOR="";
        String pack_sql = "select SJQID,bgxh,DOCTADVISENO,EXECUTOR from l_jytmxx_package where bgxh='" + parcelCode + "'";
        List<Map<String, Object>> packlist = jdbcTemplate.queryForList(pack_sql);
        log.info(pack_sql);
        int packnums = packlist.size();
        for (int k = 0; k < packlist.size(); k++) {
            Map<String, Object> packmap = packlist.get(k);
            sjqid = packmap.get("SJQID") + "";
            DOCTADVISENO = packmap.get("DOCTADVISENO") + "";
            EXECUTOR = packmap.get("EXECUTOR") + "";
            log.info("packlist:"+packmap);

            String tm_sql = "select patientid,patientname,sampletype,section,bed_no from l_jytmxx where DOCTADVISENO='" + DOCTADVISENO + "'";
            List<Map<String, Object>> tm_list = jdbcTemplate.queryForList(tm_sql);
            log.info(tm_sql);
            log.info("tm_list:"+tm_list);
            String medicalRecordNo = "";
            String nursingDeptName = "";
            String bedNo = "";
            String patientName = "";
            String samplingType = "";
            for (int m = 0; m < tm_list.size(); m++) {
                Map<String, Object> tmmap = tm_list.get(m);
                medicalRecordNo = tmmap.get("PATIENTID") + "";
                patientName = tmmap.get("PATIENTNAME") + "";
                samplingType = tmmap.get("SAMPLETYPE") + "";
                nursingDeptName = tmmap.get("SECTION") + "";
                bedNo = tmmap.get("BED_NO") + "";


                barCodeList.setBarCode(DOCTADVISENO);
                if(!bedNo.isEmpty()&&!bedNo.equals("")){
                    barCodeList.setBedNo(bedNo);
                }
                barCodeList.setMedicalRecordNo(medicalRecordNo);
                barCodeList.setPatientName(patientName);

                String yb_sql = "select SAMPLEDESCRIBE from l_sampletype where sampletype='" + samplingType + "'";
                List<Map<String, Object>> yb_list = jdbcTemplate.queryForList(yb_sql);
                log.info(yb_sql);
                String samplingTypeName = "";
                for (int n = 0; n < yb_list.size(); n++) {
                    Map<String, Object> ybmap = yb_list.get(n);
                    samplingTypeName = ybmap.get("SAMPLEDESCRIBE") + "";
                }
                barCodeList.setSamplingType(samplingTypeName);
                barCodeList.setNursingDeptName(nursingDeptName);
                barCodeInfo.add(barCodeList);
            }
        }

        String ks_sql = "select ksmc from gy_ksdm where ksdm='" + sjqid + "'";
        List<Map<String, Object>> ks_list = jdbcTemplate.queryForList(ks_sql);
        log.info(ks_sql);
        log.info("ks_list:"+ks_list);

        String originDeptName = "";
        for (int k = 0; k < ks_list.size(); k++) {
            Map<String, Object> ksmap = ks_list.get(k);
            originDeptName = ksmap.get("KSMC") + "";

        }

        String zg_sql = "select xm from gy_zgxx where zgid='" + EXECUTOR + "'";
        List<Map<String, Object>> zg_list = jdbcTemplate.queryForList(zg_sql);
        log.info(zg_sql);
        log.info("zg_list:"+zg_list);

        String reqEmpName = "";
        for (int k = 0; k < zg_list.size(); k++) {
            Map<String, Object> zgmap = zg_list.get(k);
            reqEmpName = zgmap.get("XM") + "";
        }

        specimenOrderRequest.setOriginDeptId(sjqid);
        specimenOrderRequest.setOriginDeptName(originDeptName);
        specimenOrderRequest.setDestinationDeptId("135");
        specimenOrderRequest.setDestinationDeptName("检验科");
        specimenOrderRequest.setParcelCode(parcelCode);
        specimenOrderRequest.setBarCodeInfo(barCodeInfo);
        specimenOrderRequest.setSpecimenNum(packnums);
        specimenOrderRequest.setReqEmpId(EXECUTOR);
        specimenOrderRequest.setReqEmpName(reqEmpName);

        specimenOrderRequestList.add(specimenOrderRequest);

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

        // 对象转JSON
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writeValueAsString(specimenOrderRequestList);
        // 封装请求体
        HttpEntity entity = new HttpEntity(jsonString, headers);

        log.info("创建工单入参："+entity);
        // 发送POST请求
        ResponseEntity<ApiResponse> response = restTemplate.postForEntity(CREATE_ORDER_URL, entity, ApiResponse.class);

        log.info("创建工单返参："+response);
        // 返回响应
        return response.getBody();
    }

    public ApiResponse cancelSpecimenOrder(CancelOrderRequest request) {
//        CancelOrderRequest cancelOrderRequest = new CancelOrderRequest();
        // 处理取消标本运送工单的逻辑
        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        // 封装请求体
        HttpEntity<CancelOrderRequest> entity = new HttpEntity<>(request, headers);
        // 发送POST请求
        ResponseEntity<ApiResponse> response = restTemplate.postForEntity(CANCEL_ORDER_URL, entity, ApiResponse.class);

        // 模拟成功响应
        return response.getBody();
    }

    //MD5加密校验
    public boolean validateAuthorization(String requestId, String from, String authorization) {
        try {
            String input = requestId + "@" + from;
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] digest = md.digest(input.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte b : digest) {
                sb.append(String.format("%02x", b));
            }
            String expectedAuthorization = sb.toString();
            return expectedAuthorization.equals(authorization);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}